package com.maixun.lib_comment.recyclerview

import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

/**
 * 作者：Lmoumou
 * 时间：2020/8/5 16:08
 */
class ViewHolderImpl(itemView: View) : RecyclerView.ViewHolder(itemView),
    BaseViewHolder {

    private val mView by lazy { SparseArray<View>() }

    @Suppress("UNCHECKED_CAST")
    override fun <T : View> getView(viewId: Int): T {
        var view = mView[viewId]
        if (view == null) {
            view = itemView.findViewById(viewId)
            mView.put(viewId, view)
        }
        return view!! as T
    }

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewGroup> getViewGroup(viewId: Int): T {
        var view = mView[viewId]
        if (view == null) {
            view = itemView.findViewById(viewId)
            mView.put(viewId, view)
        }
        return view!! as T
    }

    /**
     * 设置TextView的文本内容
     * */
    override fun setText(viewId: Int, content: CharSequence): BaseViewHolder {
        val view: TextView = getView(viewId)
        view.text = content
        return this
    }

    override fun setImageResource(viewId: Int, resId: Int): BaseViewHolder {
        val view: ImageView = getView(viewId)
        view.setImageResource(resId)
        return this
    }

    override fun loadPicture(viewId: Int, picturePath: String, imageLoader: HolderImageLoader) {
        val view: ImageView = getView(viewId)
        imageLoader.loadImage(view, picturePath)
    }


    /**
     * 图片加载器
     * */
    abstract class HolderImageLoader {
        abstract fun loadImage(iv: ImageView, path: String)
    }

}